package com.example.demo.core.util;

import com.example.demo.core.exception.NotFoundException;
import com.example.demo.core.exception.ProgramException;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.springframework.expression.spel.ast.NullLiteral;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author yujie
 */
public class XmlUtil {

    private final static String DEFAULT_POM_PATH = "pom.xml";

    private final static String DEFAULT_VALUE = null;

    /**
     * 读取默认路径的pom.xml
     * @return model
     */
    public static Model getPomModel(){
        return getPomModel(DEFAULT_VALUE);
    }

    /**
     * 读取指定pom.xml
     *
     * @param path 指定路径pom.xml
     * @return model
     */
    public static Model getPomModel(String path) {
        try {
            FileInputStream fis = new FileInputStream(new File((path == null) ? DEFAULT_POM_PATH : path));
            MavenXpp3Reader reader = new MavenXpp3Reader();
            return reader.read(fis);
        } catch (FileNotFoundException e) {
            throw new NotFoundException("文件找不到");
        } catch (XmlPullParserException e) {
            throw new ProgramException("xml解析错误");
        } catch (IOException e) {
            throw new ProgramException("IO异常");
        }


    }
}
